﻿/*
 * (c) Stefan Bojarovski 2010
 * */
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ASTBuilder
{
    class WhileNode : NodesCollection, ITreeNode
    {
        private LexemeType lexType = LexemeType.WHILE_OPERATOR;
        private ITreeNode Condition; //Boolean expression or identifier
        private ITreeNode Body; // Block

        public WhileNode(ITreeNode someExpr, ITreeNode someBlock)
        {
            Condition = someExpr;
            Body = someBlock;
        }
        public LexemeType getLexemeType()
        {
            return lexType;
        }
        public void printNode(String parentLevel, StreamWriter someStream)
        {
            someStream.WriteLine(parentLevel + " " + "While Operator: ");
            someStream.WriteLine(parentLevel + " " + "Condition: ");
            Condition.printNode(parentLevel + " ", someStream);
            someStream.WriteLine(parentLevel + " " + "Body: ");
            Body.printNode(parentLevel + " ", someStream);
        }
        public List<Command> evalNode(ref Direction next,
                                        ref Dictionary<String, Pair<IdentifierType, object>> Environment)
        {
            List<Command> result = new List<Command>();
            if (next != Direction.JUMP)
            {
                bool condition = (bool)Condition.evalNode(ref next, ref Environment)[0].getIdValue();


                while (condition)
                {
                    List<Command> singleStep = Body.evalNode(ref next, ref Environment);
                    foreach (Command command in singleStep)
                    {
                        result.Add(command);
                    }
                    condition = (bool)Condition.evalNode(ref next, ref Environment)[0].getIdValue();
                }
                return result;
            }
            else
            {
                result.Add(new Command(CommandType.VOID, null, null));
                return result;
            }
        }
    }
}
